<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { createTableDataApi, deleteTableDataApi, updateTableDataApi, getTableDataApi } from "@/api/table"
import { getSysAuthorityRoute, addSysAuthorityRoute, delSysAuthorityRoute } from "@/api/sysAuthorityRoute"

import { type GetTableData } from "@/api/table/types/table"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { Search, Refresh, CirclePlus, Delete, Download, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { formatDate } from "@/utils/index"
import * as ElementPlusIconsVue from "@element-plus/icons-vue"

defineOptions({
  // 命名当前组件
  name: "routerclass"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const elList = reactive<any>([]) //icon图标list

//#region 增
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = reactive({
  name: "",
  path: "",
  pid: "",
  sort: "",
  image: "",
  isMenu: 1
})
const formRules: FormRules = reactive({
  // name: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  // path: [{ required: true, trigger: "blur", message: "请输入密码" }]
})
const handleCreate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        addSysAuthorityRoute(formData)
          .then(() => {
            ElMessage.success("新增成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      } else {
        addSysAuthorityRoute({
          id: currentUpdateId.value,
          ...formData
        })
          .then(() => {
            ElMessage.success("修改成功")
            getTableData()
          })
          .finally(() => {
            dialogVisible.value = false
          })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}
// 重置数据
const resetForm = () => {
  currentUpdateId.value = undefined
  formData.name = ""
  formData.path = ""
  formData.pid = ""
  formData.sort = ""
  formData.image = ""
  formData.isMenu = 1
}
//#endregion

//#region 删
const handleDelete = (row: GetTableData) => {
  ElMessageBox.confirm(`正在删除路由：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delSysAuthorityRoute([row.id]).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const currentUpdateId = ref<undefined | string>(undefined)
const handleUpdate = (row: any) => {
  currentUpdateId.value = row.id
  formData.name = row.name
  formData.path = row.path
  formData.pid = row.pid
  formData.sort = row.sort
  formData.image = row.image
  formData.isMenu = row.isMenu
  dialogVisible.value = true
}
//#endregion

//#region 查
const tableData = ref<GetTableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  path: ""
})
// 获取列表数据
const getTableData = () => {
  loading.value = true
  getSysAuthorityRoute({
    page: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.name || undefined,
    path: searchData.path || undefined
  })
    .then((res) => {
      paginationData.total = res.data.total
      console.log(res)

      tableData.value = res.data.records
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

for (const key in ElementPlusIconsVue) {
  elList.push({
    value: key,
    label: key
  })
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="路由名">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="路由路径">
          <el-input v-model="searchData.path" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增路由</el-button>
          <!-- <el-button type="danger" :icon="Delete">批量删除</el-button> -->
        </div>
        <div>
          <!-- <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip> -->
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="id" label="id" align="center" />
          <el-table-column prop="name" label="路由名" align="center" />
          <el-table-column prop="path" label="路由路径" align="center" />
          <el-table-column prop="pid" label="父级ID" align="center" />
          <el-table-column prop="sort" label="排序值" align="center" />
          <el-table-column prop="image" label="图标" align="center">
            <template #default="scope">
              <!-- {{ scope.row['image']  }} -->
              <el-icon>
                <component :is="scope.row['image']" />
              </el-icon>
            </template>
          </el-table-column>

          <el-table-column prop="isMenu" label="是否作为导航栏" align="center">
            <template #default="scope">
              <div>{{ scope.row.isMenu == "0" ? "不作为导航栏" : "导航栏" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
            <template #default="scope">
              <div>{{ formatDate(scope.row.createTime) }}</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="currentUpdateId === undefined ? '新增路由' : '修改路由'"
      @close="resetForm"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="路由名">
          <el-input v-model="formData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="path" label="路由路径">
          <el-input v-model="formData.path" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="pid" label="父级ID">
          <el-input v-model="formData.pid" placeholder="(默认0没有父级ID)" />
        </el-form-item>
        <el-form-item prop="sort" label="排序值">
          <el-input v-model="formData.sort" placeholder="排序值-越小越靠前" />
        </el-form-item>
        <el-form-item prop="image" label="图标">
          <!-- <el-input v-model="formData.image" placeholder="请输入" /> -->
          <el-select v-model="formData.image" placeholder="Select" clearable filterable>
            <el-option v-for="item in elList" :key="item.value" :label="item.label" :value="item.value">
              <span style="float: left">{{ item.label }}</span>
              <div style="float: right; color: var(--el-text-color-secondary); font-size: 13px; display: inline-block">
                <el-icon>
                  <component :is="item.label.length > 2 && item.label.length < 20 ? item.label : 'Edit'" />
                </el-icon>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isMenu" label="是否导航栏">
          <el-radio-group v-model="formData.isMenu" class="ml-4">
            <el-radio :label="0" size="large">不作导航栏</el-radio>
            <el-radio :label="1" size="large">导航栏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
